/*
 * @Author: 周海 zhouhaib@yonyou.com
 * @Date: 2022-12-17 11:32:53
 * @LastEditors: Zhouhai 497675647@qq.com
 * @LastEditTime: 2024-04-16 16:47:54
 */
import { Button, Col, Form, Input, Select, Modal, Radio, Row, Space } from 'antd';
import React, { useEffect, useState } from 'react'
import BillCard from '@/components/BillCard';
import { useStore } from '@/store';
import { delSysjob, addSysjob, updateSysjob } from '@/api/monitor/sysjob';
import { SysJobDomain } from '@/type.d/monitor/sysjob';

import './index.less';
import CronInput from './components/inputCron';

interface SysJobCardProp {
    sysJobStatusOptions: any[];
    sysJobGroupOptions: any[];
    /**
     * 卡片数据 受控
     */
    cardData: SysJobDomain;
    /**
     * 卡片新增时的默认数据
     */
    newdata?: SysJobDomain;
    /**
     * 列表数据
     */
    tableListDataSource: SysJobDomain[];
    /**
     * 更新列表数据
     */
    setTableListDataSource: (data: SysJobDomain[]) => void;

    setIsedit?: (isedit: boolean) => void;

    isedit?: boolean;
    /**
     * 跳转到列表状态
     */
    onBack?: (e?: React.MouseEvent<HTMLElement>) => void;
}
const SysJobCard: React.FC<SysJobCardProp> = ((props: SysJobCardProp) => {
    const {
        cardData,
        newdata = {},
        tableListDataSource,
        setTableListDataSource,
        setIsedit,
        isedit = false,
        onBack
    } = props;
    const { layoutStore } = useStore();
    const [selectdata, setSelectdata] = useState<SysJobDomain>(cardData);
    const [oldSelectdata, setOldSelectdata] = useState<SysJobDomain>({});//编辑状态临时保存选中的菜单树数据
    const [formRef] = Form.useForm<SysJobDomain>();

    const intCardData = (_cardData: SysJobDomain) => {
        setSelectdata(_cardData)
        setOldSelectdata({})
    }


    const addCardData = (_cardData: SysJobDomain) => {
        setSelectdata(_cardData)
        setOldSelectdata({ ...selectdata })
        setIsedit?.(true)
    }

    const editCardData = () => {
        setOldSelectdata({ ...selectdata })
        setIsedit?.(true)
    }

    const resetCardData = () => {
        setSelectdata({ ...oldSelectdata })
        setOldSelectdata({})
    }

    const onDelete = (dedata: SysJobDomain) => {
        if (dedata.jobId) {
            layoutStore.OpenSpanning()
            delSysjob(dedata.jobId).then(() => {
                setSelectdata({})
                setOldSelectdata({})
                setTableListDataSource(tableListDataSource.filter((item) => {
                    return item.jobId !== dedata.jobId
                }))
            }).finally(() => {
                layoutStore.CloseSpanning()
            })
        }

    }

    useEffect(() => {//从列表跳转到卡片，如果数据发生了变化，更新数据
        intCardData(cardData)
    }, [])


    useEffect(() => {
        formRef.resetFields()
        if (selectdata) {
            formRef?.setFieldsValue({ ...selectdata });
        } else {
            formRef?.setFieldsValue({});
        }
    }, [selectdata])


    /**
     * 表单字段配置
     */
    const cardItems: JSX.Element =
        <Row>
            <Col md={8} xl={6} hidden>
                <Form.Item
                    name="jobId"
                    label="任务ID"
                >
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6} >
                <Form.Item
                    name="jobName"
                    label="任务名称"
                >
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6} >
                <Form.Item
                    name="jobGroup"
                    label="任务组名"
                >
                    <Select options={props.sysJobGroupOptions} />
                </Form.Item>
            </Col>
            <Col md={24} xl={24} >
                <Form.Item
                    name="invokeTarget"
                    label="调用目标字符串"
                    rules={[{
                        required: true,
                        message: '此项为必填项',
                    }]}
                >
                    <Input.TextArea />
                </Form.Item>
            </Col>
            <Col md={8} xl={6} >
                <Form.Item
                    name="cronExpression"
                    label="cron执行表达式"
                >
                    <CronInput />
                </Form.Item>
            </Col>
            <Col md={8} xl={6} >
                <Form.Item
                    name="misfirePolicy"
                    label="计划执行错误策略"
                >
                    <Radio.Group
                        options={[
                            { label: '立即执行', value: '1' },
                            { label: '执行一次', value: '2' },
                            { label: '放弃执行', value: '3' },
                        ]}
                    />
                </Form.Item>
            </Col>
            <Col md={8} xl={6} >
                <Form.Item
                    name="concurrent"
                    label="是否并发执行"
                >
                    <Radio.Group
                        options={[
                            { label: '允许', value: '0' },
                            { label: '禁止', value: '1' },
                        ]}
                    />
                </Form.Item>
            </Col>
            <Col md={8} xl={6} >
                <Form.Item
                    name="status"
                    label="状态"
                >
                    <Radio.Group options={props.sysJobStatusOptions} />
                </Form.Item>
            </Col>
            <Col md={24} xl={24} >
                <Form.Item
                    name="remark"
                    label="备注信息"
                >
                    <Input.TextArea />
                </Form.Item>
            </Col>
            <Col md={8} xl={6} hidden>
                <Form.Item
                    name="createBy"
                    label="创建者"
                >
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6} hidden>
                <Form.Item
                    name="createTime"
                    label="创建时间"
                >
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6} hidden>
                <Form.Item
                    name="updateBy"
                    label="更新者"
                >
                    <Input />
                </Form.Item>
            </Col>
            <Col md={8} xl={6} hidden>
                <Form.Item
                    name="updateTime"
                    label="更新时间"
                >
                    <Input />
                </Form.Item>
            </Col>
        </Row>
        ;


    const cardbuttons = (
        <Space>
            <Button
                size='small'
                key="add"
                type="primary"
                onClick={() => {
                    addCardData({ ...newdata })
                }}
            >
                新增
            </Button>
            <Button
                size='small'
                key="edit"
                type="primary"
                disabled={selectdata?.jobId ? false : true}
                onClick={() => {
                    editCardData()
                }}
            >
                修改
            </Button>
            <Button
                size='small'
                key="delete"
                type="primary"
                disabled={selectdata?.jobId ? false : true}
                onClick={() => {
                    Modal.confirm({
                        okText: '确定',
                        cancelText: '取消',
                        title: '系统提示',
                        content: '确定要删除数据吗？',
                        type: 'warning',
                        onOk: () => {
                            onDelete(selectdata)
                        }
                    }
                    )

                }}
            >
                删除
            </Button>
        </Space>
    )

    const onSave = () => {
        formRef.validateFields().then(() => {
            const data: SysJobDomain = formRef.getFieldsValue?.() || {};
            if (!selectdata.jobId) {//新增
                layoutStore.OpenSpanning()
                addSysjob({ ...selectdata, ...data }).then((res) => {
                    intCardData(res.data)//更新卡片数据
                    tableListDataSource.push(res.data)
                    setTableListDataSource([...tableListDataSource])
                    setIsedit?.(false)
                }).finally(() => {
                    layoutStore.CloseSpanning()
                })
            } else {//更新
                layoutStore.OpenSpanning()
                updateSysjob({ ...selectdata, ...data }).then((res) => {
                    intCardData(res.data)//更新卡片数据
                    setTableListDataSource(tableListDataSource.map((item) => {
                        if (item.jobId === res.data.jobId) {
                            return res.data
                        } else {
                            return item
                        }
                    }))
                    setIsedit?.(false)
                }).finally(() => {
                    layoutStore.CloseSpanning()
                })
            }
        })
    }


    const editbuttions = (
        <Space>
            <Button
                size='small'
                key="save"
                type="primary"
                onClick={() => {
                    onSave()
                }}
            >
                保存
            </Button>
            <Button
                size='small'
                key="cancel"
                type="primary"
                onClick={() => {
                    resetCardData()
                    setIsedit?.(false)
                }}
            >
                取消
            </Button>
        </Space>
    )

    return (
        <BillCard
            formid='jobId'
            key={'SysJobCard'}
            formRef={formRef}
            isedit={isedit}
            extraButton={isedit ? editbuttions : cardbuttons}
            onBack={onBack}
            title={'定时任务调度'}
            cardItem={cardItems}
        />
    )
})
export default SysJobCard;